package com.wbdgj.ui.word_compaign;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.wbdgj.R;
import com.wbdgj.adapter.WordTatterItemAdapter;
import com.wbdgj.adapter.WordTrueTatterItemAdapter;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.ui.login.LoginActivity;
import com.wbdgj.utils.MyGridView;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;
import com.wbdgj.utils.dialog.ConfirmDialog;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit2.Call;

public class WordTatterActivity extends BaseActivity implements PtrHandler {

    private Context context = this;
    @BindView(R.id.pfl_root)
    PtrClassicFrameLayout pfl_root;

     @BindView(R.id.spGridView)
     MyGridView spGridView;

    @BindView(R.id.wordGridView)
    MyGridView wordGridView;

    @BindView(R.id.ljheBtn)
    Button ljheBtn;

    @BindView(R.id.rule_intro)
    TextView rule_intro;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rule_content)
    TextView rule_content;

    WordTatterItemAdapter tatterItemAdapter;
    private List<LinkedTreeMap> tatterItemList;

    private List<LinkedTreeMap> tatterFlaseList;

    WordTrueTatterItemAdapter wordTrueTatterItemAdapter;
    private List<LinkedTreeMap> tatterTrueList;

    private String[] KEYS;

    private String rule_title;

    private int left_quantity;
    private int coupon_num;
    private String rule_code;
    private DecimalFormat decimalFormat;
    private boolean ljhcBoolean = true;

    @BindView(R.id.bgImg)
    ImageView bgImg;

    private String box_img;

    private int right_quantity = 0;

    @Override
    protected int getLayoutResId() {
        return R.layout.ui_word_tatter;
    }

    @Override
    protected void initView() {
        decimalFormat = new DecimalFormat("###################.###########");
        rule_code = getIntent().getStringExtra("rule_code");
        rule_title = getIntent().getStringExtra("rule_title");
        pfl_root.setEnabledNextPtrAtOnce(true);
        pfl_root.setLastUpdateTimeRelateObject(this);
        pfl_root.setPtrHandler(this);
        pfl_root.setKeepHeaderWhenRefresh(true);
        bg();
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        bg();
        pfl_root.refreshComplete();
    }

    @OnClick(value = {R.id.ljheBtn})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ljheBtn:
                if (ljhcBoolean){
                    ToastUtils.toastShort("缺少字，无法合成！");
                    return;
                }
                final ConfirmDialog confirmDialog = new ConfirmDialog(context, "确定合成吗？", 1);
                confirmDialog.show();
                confirmDialog.setCanceledOnTouchOutside(false);
                confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        confirmDialog.dismiss();
                        singlemore();
                    }

                    @Override
                    public void doCancel() {
                        confirmDialog.dismiss();
                    }
                });
                break;
        }
    }

    private void singlemore() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().singlemore(rule_code, Arrays.toString(KEYS).replace("[", "").replace("]","").replace(" ",""), BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    List<LinkedTreeMap> linkedTreeMapDate = (List<LinkedTreeMap>) linkedTreeMap.get("data");
                    setResult(2);
                    finish();
                    BaseApplication.getInstance().setlinkedTreeMapList(linkedTreeMapDate);
                    startActivityForResult(new Intent(context, CouponCompaignDialogResultActivity.class), 1);

                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    final ConfirmDialog confirmDialog = new ConfirmDialog(context,userModelBaseResultModel.getResultMsg(), 8);
                    confirmDialog.show();
                    confirmDialog.setCanceledOnTouchOutside(false);
                    confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            confirmDialog.dismiss();
                        }

                        @Override
                        public void doCancel() {
                            confirmDialog.dismiss();
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        if(resultCode == 3){
            setResult(2);
            finish();
        }
    }

    private void bg() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().bg(rule_code, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    LinkedTreeMap dateLink = (LinkedTreeMap) linkedTreeMap.get("data");
                    Glide.with(context).load(dateLink.get("bg_img")+"").error(R.mipmap.ui_word_tatter).into(bgImg);
                    box_img = dateLink.get("box_img")+"";
                    find(rule_code, rule_title);
                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
    }

    private void find(String rule_code, final String rule_title) {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().find(rule_code, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.TOKEN));
        call.enqueue(new OnResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    LinkedTreeMap linkedTreeMapData = (LinkedTreeMap) linkedTreeMap.get("data");
                    rule_intro.setText(linkedTreeMapData.get("rule_intro")+"");
                    title.setText(linkedTreeMapData.get("rule_title")+"");
                    rule_content.setText(linkedTreeMapData.get("rule_content")+"");

                    tatterItemList = new ArrayList<>() ;
                    tatterItemList = (List<LinkedTreeMap>) linkedTreeMapData.get("material_package");
                    List<LinkedTreeMap> couponList = (List<LinkedTreeMap>) linkedTreeMap.get("coupon");

                    tatterTrueList = new ArrayList<>();
                    right_quantity = 0;

                    for(int i = 0; i < tatterItemList.size(); i ++){
                        int left_quantity = Integer.parseInt(decimalFormat.format(tatterItemList.get(i).get("left_quantity")));
                        int numQ = 0;
                        right_quantity = right_quantity + left_quantity;
                        for (int j = 0; j < couponList.size(); j++){
                            if((tatterItemList.get(i).get("left_key")+"").equals(couponList.get(j).get("P_KEY"))){
                                tatterTrueList.add(couponList.get(j));
                                numQ++;
                                if(left_quantity == numQ){
                                    break;
                                }
                            }
                        }
                    }

                    tatterFlaseList = new ArrayList<>();
                    for (int i = 0 ; i < right_quantity; i++){
                        tatterFlaseList.add(new LinkedTreeMap());
                    }

                    tatterItemAdapter = new WordTatterItemAdapter(context, tatterFlaseList,box_img, coupon_num);
                    spGridView.setAdapter(tatterItemAdapter);


                    if(tatterTrueList.size() > 0){
                        wordTrueTatterItemAdapter = new WordTrueTatterItemAdapter(context, tatterTrueList, "", 0);
                        wordGridView.setAdapter(wordTrueTatterItemAdapter);
                    }


                    if(tatterTrueList.size() == right_quantity){
                        ljhcBoolean = false;
                        ljheBtn.setBackgroundResource(R.mipmap.tatter_button_true);
                        ljheBtn.setTextColor(getResources().getColor(R.color.colorBtnTatter));
                        KEYS = new String[tatterTrueList.size()];
                        for (int i = 0; i < tatterTrueList.size(); i ++){
                            KEYS[i] = tatterTrueList.get(i).get("M_KEY")+"";
                        }
                    }else{
                        ljhcBoolean = true;
                        ljheBtn.setBackgroundResource(R.mipmap.tatter_button_false);
                        ljheBtn.setTextColor(getResources().getColor(R.color.white));
                    }


                }else if (userModelBaseResultModel.getResultCode().equals("1111")){
                    ToastUtils.toastShort("账号没有登录或在其它地方登录");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, "");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "2");
                    PushManager.getInstance().unBindAlias(context, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE), false, BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.CID));
                    Intent intent = new Intent(context, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private  static List<LinkedTreeMap> filter(List<LinkedTreeMap> fruit, String board, String name){
        List<LinkedTreeMap> f = new ArrayList<>();
        for (LinkedTreeMap s : fruit){
            if((s.get(name)+"").equals(board)){
                f.add(s);
            }
        }
        return f;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 0){
            setResult(1);
            finish();
        }
    }
}
